﻿namespace Reviewer.Web.UI
{
    using System;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Reflection;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Reviewer.Entities.MetadataInfo;
    using AjaxControlToolkit;
    using SD = System.Drawing;

    public class MetadataImagePropertyControl : MetadataPropertyControl
    {
        protected HiddenField imageFilename;
        private Image image = new Image();
        protected Button changeButton = new Button();
        protected IImageUploaderControl imageUploader;
        protected ModalPopupExtender popupExtender = new ModalPopupExtender();
        protected Panel popupPanel = new Panel();
        protected Button popupCancelButton = new Button();

        public MetadataImagePropertyControl(PropertyInfo property)
            : base(property)
        {
        }

        protected override void CreateChildControlsEx()
        {
            this.imageFilename = new HiddenField();
            this.Controls.Add(this.imageFilename);
            this.image.ID = this.ID + "_im" + this.propertyInfo.Name;
            this.image.CssClass = "gallery";
            this.Controls.Add(this.image);

            this.Controls.Add(new LiteralControl("<br /><br />"));
            this.changeButton.ID = "uiBtnChangeImage";
            this.changeButton.Text = "Skift";
            this.changeButton.Click += new EventHandler(ChangeImageButtonClick);
            this.Controls.Add(this.changeButton);

            this.popupExtender.CacheDynamicResults = false;
            this.popupExtender.DropShadow = true;
            this.popupExtender.BackgroundCssClass = "modalBG";
            this.popupExtender.RepositionMode = ModalPopupRepositionMode.RepositionOnWindowResizeAndScroll;

            this.Controls.Add(this.popupExtender);

            this.popupPanel.Width = 400;
            this.popupPanel.BackColor = SD.Color.White;
            this.popupPanel.BorderColor = SD.Color.Black;
            this.popupPanel.BorderStyle = BorderStyle.Solid;
            this.popupPanel.BorderWidth = 1;
            this.popupPanel.ID = "uiPnlPopup";

            Panel popupPanelTop = new Panel();
            popupPanelTop.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

            this.popupCancelButton.ID = "uiBtnCancelPopup";
            this.popupCancelButton.Text = "X";
            popupPanelTop.Controls.Add(this.popupCancelButton);

            this.popupPanel.Controls.Add(popupPanelTop);
            this.popupExtender.CancelControlID = this.popupCancelButton.ID;

            this.Controls.Add(this.popupPanel);
            this.popupExtender.PopupControlID = this.popupPanel.ID;
            this.popupExtender.TargetControlID = this.changeButton.ID;

            var attribute = Attribute.GetCustomAttribute(this.propertyInfo, typeof(MetadataImagePropertyAttribute)) as MetadataImagePropertyAttribute;
            if (attribute.MaximumHeight != 0)
            {
                this.image.Height = attribute.MaximumHeight;
            }

            if (attribute.MaximumWidth != 0)
            {
                this.image.Width = attribute.MaximumWidth;
            }

            this.Controls.Add(new LiteralControl("<br />"));
            this.imageUploader = Page.LoadControl("~/CMSV2/Controls/ImageUploader.ascx") as IImageUploaderControl;
            this.imageUploader.MaxHeight = attribute.MaximumHeight;
            this.imageUploader.MaxWidth = attribute.MaximumWidth;
            this.imageUploader.ExactSize = attribute.ExactSize;
            this.imageUploader.ImageTransformationComplete += new ImageTransformationCompleteDelegate(imageUploader_ImageTransformationComplete);
            this.popupPanel.Controls.Add(this.imageUploader as Control);
        }

        void ChangeImageButtonClick(object sender, EventArgs e)
        {
            this.EnsureChildControls();

            this.popupExtender.Show();
        }

        void imageUploader_ImageTransformationComplete(object sender, System.Drawing.Image transformedImage)
        {
            this.EnsureChildControls();

            var fileName = String.Empty;
            if (!String.IsNullOrEmpty(this.imageFilename.Value))
            {
                fileName = this.imageFilename.Value;
            }
            else
            {
                var subPath = String.Empty;
                var attribute = Attribute.GetCustomAttribute(this.propertyInfo, typeof(MetadataImagePropertyAttribute)) as MetadataImagePropertyAttribute;
                if (attribute != null)
                {
                    if (!String.IsNullOrEmpty(attribute.Path))
                    {
                        subPath = attribute.Path + "/";
                    }
                }

                fileName = "/images/" + subPath + Guid.NewGuid().ToString("N") + ".png";
            }

            var psysicalFile = MapPathSecure(fileName);
            if (!String.IsNullOrEmpty(this.imageFilename.Value) && File.Exists(psysicalFile))
            {
                File.Delete(psysicalFile);
            }

            this.imageFilename.Value = fileName;

            if (File.Exists(psysicalFile))
            {
                var indexer = 1;

                string tempFilename = String.Empty;
                do
                {
                    tempFilename = this.imageFilename.Value.Replace(".png", "_" + indexer.ToString() + ".png");
                    psysicalFile = MapPathSecure(tempFilename);
                } while (File.Exists(psysicalFile));

                this.imageFilename.Value = tempFilename;
            }

            if (!Directory.Exists(Path.GetDirectoryName(psysicalFile)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(psysicalFile));
            }

            transformedImage.Save(psysicalFile, ImageFormat.Png);

            this.image.ImageUrl = this.imageFilename.Value;
        }

        public override void Reset()
        {
            EnsureChildControls();

            this.image.ImageUrl = String.Empty;

            foreach (Control c in this.Controls)
            {
                MethodInfo method = Controls.GetType().GetMethod("Reset");
                if (method != null)
                {
                    method.Invoke(c, null);
                }
            }
        }

        public override void SetProperty(object item)
        {
            this.EnsureChildControls();

            this.propertyInfo.SetValue(item, this.imageFilename.Value, null);
        }

        public override void GetProperty(object item)
        {
            this.EnsureChildControls();

            this.image.ImageUrl = this.propertyInfo.GetValue(item, null).ToString();
            this.imageFilename.Value = this.propertyInfo.GetValue(item, null).ToString();
        }

    }
}